package database

import (
	"context"
	"sync"

	"du/config"
	"fmt"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)


var (
	mongoOnce sync.Once
	mongoInstance   *mongo.Database
)

func InitMongoDB() (*mongo.Database, error) {
	mongoOnce.Do(func() {
		dsn := fmt.Sprintf("mongodb://%s:%s",
			config.App.Mongodb.Host,
			config.App.Mongodb.Port)

		// 连接 MongoDB
		client, err := mongo.Connect(
			context.TODO(), options.Client().ApplyURI(dsn))
		if err != nil {
			return
		}

		defer client.Disconnect(context.TODO())

		// 获取集合
		// collection := client.Database("mydb").Collection("users")

		mongoDB := client.Database(config.App.Mongodb.Database)
		mongoInstance = mongoDB
	})

	return mongoInstance, nil
}

func GetMongoDB() *mongo.Database {
	return mongoInstance
}